package com.hlingsoft.kkh.action.admin;

import cn.jpush.api.utils.StringUtils;

import com.google.gson.Gson;
import com.hlingsoft.kkh.entity.*;
import com.hlingsoft.kkh.entity.vo.JsonVo;
import com.hlingsoft.kkh.entity.vo.PageVo;
import com.hlingsoft.kkh.util.Common;
import com.hlingsoft.kkh.util.HttpUtils;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by selbylei on 2015/6/11.
 */

@Controller
@RequestMapping("/admin/appUser")
public class AdminAppUserAction extends AdminBaseAction {

    @RequestMapping(value = "/list.htm")
    public String allList(
            HttpServletRequest request,
            ModelMap modelMap) {
//        List<AppUser> appUserList = userDao.getAppUserWithNone1();
        List<AppUser> appUserList = userDao.getAppUserWithNone(0,10);
        for (AppUser appUser : appUserList) {
            String interests = "";
            appUser.setProfession(professionDao.getProfessionById(appUser.getProfessionId()).getName());
            String interestIds = appUser.getInterestIds();
            List<Integer> integerList = Common.strToIntegerList(interestIds);
            for (Integer interestId : integerList) {
                String interest = interestDao.getInterestById(interestId).getName();
                interests += interest + ",";
            }
            if (interests.length() > 0) {
                interests = interests.substring(0, interests.length() - 1);
            }
            appUser.setInterests(interests);
        }
        modelMap.put("appUserList", appUserList);

        return "system/appUser/list";
    }


    /**
     * 禁用账号
     *
     * @param appUserId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public JsonVo<String> delete(@RequestParam(value = "appUserId") long appUserId,
                                 ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();

        Date now = new Date();
        //删除相关的活动
        List<Events> eventsList = eventsDao.getEventsByAppUserIdWithNone(appUserId);
        if (eventsList.size() > 0) {
            for (Events events : eventsList) {
                events.setAvailable(0);
                events.setUpdateTime(now);
                eventsDao.updateEvents(events);
            }
        }

        //删除相关的跟帖
        List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByAppUserIdWithNone(appUserId);
        if (eventCommentsList.size() > 0) {
            for (EventComments eventComments : eventCommentsList) {
                eventComments.setAvailable(0);
                eventComments.setUpdateTime(now);
                eventCommentsDao.updateEventComments(eventComments);
            }
        }

        //删除收藏记录
        List<Collect> collectList = collectDao.getByAppUserIdWithNone(appUserId);
        if (collectList.size() > 0) {
            for (Collect collect : collectList) {
                collect.setAvailable(0);
                collect.setUpdateTime(now);
                collectDao.updateCollect(collect);
            }
        }


        //删除点赞记录
        List<Likes> likesList = likesDao.getLikesByAppUserIdWithNone(appUserId);
        if (likesList.size() > 0) {
            for (Likes likes : likesList) {
                likes.setUpdateTime(now);
                likes.setAvailable(0);
                likesDao.updateLikes(likes);
            }
        }

        //删除关注记录
        List<Focus> focusList = focusDao.getFocusByAppUserIdWithNone(appUserId);
        if (focusList.size() > 0) {
            for (Focus focus : focusList) {
                focus.setAvailable(0);
                focusDao.updateFocus(focus);
            }
        }

        //删除用户举报记录
        List<Feedback> feedbackList = feedbackDao.getFeedbackByAppUserIdWithNone(appUserId);
        if (feedbackList.size() > 0) {
            for (Feedback feedback : feedbackList) {
                feedback.setAvailable(0);
                feedback.setUpdateTime(now);
                feedbackDao.updateFeedback(feedback);
            }
        }

        //删除用户图片
        List<Image> imageList = imageDao.getImageByAppUserIdWithNone(appUserId);
        if (imageList.size()>0 ){
            for (Image image:imageList){
                image.setAvailable(0);
                image.setUpdateTime(now);
                imageDao.updateImage(image);
            }
        }

        //删除用户相关的通知
        List<Notification> notificationList = notificationDao.getNotificationByAppUserIdWithNone(appUserId);
        if (notificationList.size()>0){
            for (Notification notification:notificationList){
                notification.setAvailable(0);
                notification.setUpdateTime(now);
                notificationDao.updateNotification(notification);
            }
        }

        //删除相关评论
        List<Reply> replyList = replyDao.getReplyByAppUserIdWithNone(appUserId);
        if (replyList.size()>0){
            for (Reply reply:replyList){
                reply.setUpdateTime(now);
                reply.setAvailable(0);
                replyDao.updateReply(reply);
            }
        }

        //删除相关举报
        List<Report> reportList=reportDao.getReportByAppUserIdWithNone(appUserId);
        if (reportList.size()>0){
            for (Report report:reportList){
                report.setUpdateTime(now);
                report.setAvailable(0);
                reportDao.updateReport(report);
            }
        }

        //删除相关评论
        List<Share> shareList=shareDao.getShareByAppUserIdWithNone(appUserId);
        if (shareList.size()>0){
            for (Share share:shareList){
                share.setUpdateTime(now);
                share.setAvailable(0);
                shareDao.updateShare(share);
            }
        }

        //删除相关聊天
        List<Chat> chatList = chatDao.getChatByAppUserIdWithNone(appUserId);
        if (chatList.size()>0){
            for (Chat chat:chatList){
                chat.setAvailable(0);
                chatDao.updateChat(chat);
            }
        }


        AppUser appUser = userDao.getUserByIdWithNone(appUserId);
        if (appUser!=null){
            appUser.setUpdateTime(now);
            appUser.setAvailable(2);
            userDao.updateUser(appUser);
        }
        json.setResult(true);
        return json;
    }


    /**
     * 禁用账号
     * @param appUserId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/takeOff.json")
    @ResponseBody
    public JsonVo<String> takeOff(@RequestParam(value = "appUserId") long appUserId,
                                 ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();

        Date now = new Date();

        //删除反馈
        List<Feedback> feedbackList = feedbackDao.getFeedbackByAppUserIdWithNone(appUserId);
        if (feedbackList.size() > 0) {
            for (Feedback feedback : feedbackList) {
                feedback.setAvailable(0);
                feedback.setUpdateTime(now);
                feedbackDao.updateFeedback(feedback);
            }
        }

        //删除相关举报
        List<Report> reportList=reportDao.getReportByAppUserIdWithNone(appUserId);
        if (reportList.size()>0){
            for (Report report:reportList){
                report.setUpdateTime(now);
                report.setAvailable(0);
                report.setStatus(2);
                reportDao.updateReport(report);
            }
        }

        //删除相关分享
        List<Share> shareList=shareDao.getShareByAppUserIdWithNone(appUserId);
        if (shareList.size()>0){
            for (Share share:shareList){
                share.setUpdateTime(now);
                share.setAvailable(0);
                shareDao.updateShare(share);
            }
        }

        //删除相关消息
        List<Notification> notificationList = notificationDao.getNotificationByAppUserIdWithNone(appUserId);
        if (notificationList.size()>0){
            for (Notification notification:notificationList){
                notification.setUpdateTime(now);
                notification.setAvailable(0);
                notificationDao.updateNotification(notification);
            }
        }

        //删除相关聊天
        List<Chat> chatList = chatDao.getChatByAppUserIdWithNone(appUserId);
        if (chatList.size()>0){
            for (Chat chat:chatList){
                chat.setAvailable(0);
                chatDao.updateChat(chat);
            }
        }


        AppUser appUser = userDao.getUserById(appUserId);
        if (appUser!=null){
            appUser.setUpdateTime(now);
            appUser.setAvailable(0);
            userDao.updateUser(appUser);
        }
        json.setResult(true);
        return json;
    }


    /**
     * 启用账号
     *
     * @param appUserId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/getOn.json")
    @ResponseBody
    public JsonVo<String> getOn(@RequestParam(value = "appUserId") long appUserId,
                                ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        Date now = new Date();

        //启动用户
        AppUser appUser = userDao.getUserByIdWithNone(appUserId);
        if (appUser!=null){
            appUser.setUpdateTime(now);
            appUser.setAvailable(1);
            userDao.updateUser(appUser);
        }
        json.setResult(true);
        return json;
    }


    /**
     * 设值为红人
     *
     * @param appUserId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/hotSet.json")
    @ResponseBody
    public JsonVo<String> hotSet(@RequestParam(value = "appUserId") long appUserId,
                                 ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        AppUser user = userDao.getUserById(appUserId);
        user.setIsHot(1);
        userDao.updateUser(user);
        json.setResult(true);
        return json;
    }

    /**
     * 取消红人
     *
     * @param appUserId
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/hotCancel.json")
    @ResponseBody
    public JsonVo<String> hotCancel(@RequestParam(value = "appUserId") long appUserId,
                                    ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        AppUser user = userDao.getUserById(appUserId);
        user.setIsHot(0);
        userDao.updateUser(user);
        json.setResult(true);
        return json;
    }


    /**
     * 搜索
     *
     * @param professionId
     * @param interestId
     * @param pageNum
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/search.htm")
    public String toSearchList(
            @RequestParam(value = "appUserId", required = false) Integer appUserId,
            @RequestParam(value = "professionId", required = false) Integer professionId,
            @RequestParam(value = "interestIds", required = false) String interestId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "p", defaultValue = "1") int pageNum,
            HttpServletRequest request,
            ModelMap modelMap) {

        PageVo<AppUser> pageVo = new PageVo<AppUser>(pageNum);
        pageVo.setRows(10);
        pageVo.basePath = HttpUtils.getBasePath(request)+"/admin/appUser/search.htm";
        List<AppUser> appUserList = new ArrayList<AppUser>();
        if (appUserId != null) {
            appUserList.add(userDao.getUserById(appUserId));
        } else {
            appUserList = userDao.getSearch(professionId, interestId, name, pageVo.getOffset(), pageVo.getRows());
        }

        List<AppUser> resultList = new ArrayList<AppUser>();
        for (AppUser appUser : appUserList) {
            String interests = "";
            appUser.setProfession(professionDao.getProfessionById(appUser.getProfessionId()).getName());
            List<Integer> integerList = Common.strToIntegerList(appUser.getInterestIds());
            if (interestId != null) {
                if (integerList.contains(Integer.valueOf(interestId))) {
                    for (Integer interestId1 : integerList) {
                        String interest = interestDao.getInterestById(interestId1).getName();
                        interests += interest + ",";
                    }
                    if (interests.length() > 0) {
                        interests = interests.substring(0, interests.length() - 1);
                    }
                    appUser.setInterests(interests);
                    resultList.add(appUser);
                }
            } else {
                for (Integer interestId1 : integerList) {
                    String interest = interestDao.getInterestById(interestId1).getName();
                    interests += interest + ",";
                }
                if (interests.length() > 0) {
                    interests = interests.substring(0, interests.length() - 1);
                }
                appUser.setInterests(interests);
                resultList.add(appUser);
            }
        }

        pageVo.setList(resultList);
        if (appUserId!=null){
            pageVo.setCount(1);
        }   else {
            pageVo.setCount(userDao.getSearchCount(professionId, interestId, name));
        }

        modelMap.put("professionList", professionDao.getProfession());
        modelMap.put("interestList", interestDao.getInterest());
        modelMap.put("name", name);
        modelMap.put("professionId", professionId);
        modelMap.put("interestId", interestId);
        modelMap.put("p", pageNum);
        modelMap.put("pageVo", pageVo);
        return "system/appUser/list";
    }


    /**
     * 添加
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/add.htm")
    public String add(HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("professionList", professionDao.getProfession());
        modelMap.put("interestList", interestDao.getInterest());
        modelMap.put("kindId", System.currentTimeMillis());
        modelMap.put("JSESSIONID", request.getSession().getId());
        return "system/appUser/add";
    }

    /**
     * 添加json
     *
     * @param name
     * @param headImage
     * @param signature
     * @param address
     * @param latitude
     * @param longitude
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/add.json")
    @ResponseBody
    public JsonVo<String> add(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "headImage") String headImage,
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "address") String address,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,

            ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {

            Date now = new Date();
            json.setResult(true);
            AppUser appUser = new AppUser();

            appUser.setName(name);
            if (!StringUtils.isEmpty(headImage) && headImage.endsWith(",")) {
                headImage = headImage.substring(0, headImage.length() - 1);
            }
            appUser.setHeadImage(headImage);
            appUser.setSignature(signature);
            appUser.setAddress(address);
            appUser.setLatitude(latitude);
            appUser.setLongitude(longitude);
            appUser.setUdId("unRegisterDevice");
            appUser.setGender(1);
            appUser.setCreateTime(now);
            appUser.setUpdateTime(now);
            appUser.setType(3);
            userDao.addUser(appUser);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("输入参数有误");
            json.setResult(false);
            return json;
        }
    }


    @RequestMapping(value = "/detail.htm")
    public String detail(@RequestParam(value = "appUserId") long appUserId,
                         HttpServletRequest request, ModelMap modelMap) {
        modelMap.put("kindId", System.currentTimeMillis());
        modelMap.put("JSESSIONID", request.getSession().getId());
        modelMap.put("appUser", userDao.getUserById(appUserId));
        return "system/appUser/edit";
    }


    @RequestMapping(value = "/edit.json")
    @ResponseBody
    public JsonVo<String> edit(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "images") String images,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "address") String address,
            @RequestParam(value = "gender") int gender,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {
            json.setResult(true);

            AppUser appUser = userDao.getUserById(appUserId);
            if (images != null) {
                appUser.setHeadImage(images);
            }
            if (name != null) {
                appUser.setName(name);
            }
            if (signature != null) {
                appUser.setSignature(signature);
            }
            if (address != null) {
                appUser.setAddress(address);
            }
            if (latitude != null) {
                appUser.setLatitude(latitude);
            }
            if (longitude != null) {
                appUser.setLongitude(longitude);
            }
            userDao.updateUser(appUser);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("输入参数有误");
            json.setResult(false);
            return json;
        }
    }


    /**
     * 用户名查找
     * @param name
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/toSearch.json")
    @ResponseBody
    public JsonVo<String> search(@RequestParam(value = "name") String name,
                                 ModelMap modelMap) {
        name = encodeStr(name);
        JsonVo<String> json = new JsonVo<String>();

        List<AppUser> appUserList = userDao.getUserByName(name);
        Gson gson=new Gson();
        json.setT(gson.toJson(appUserList));
        json.setResult(true);
        return json;
    }

    public static boolean isContainsChinese(Pattern pat, String str) {
        Matcher matcher = pat.matcher(str);
        boolean flg = false;
        if (matcher.find()) {
            flg = true;
        }
        return flg;
    }

    public String encodeStr(String str) {
        try {
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

}
